package com.ruoyi.ftrl.mqtt.service;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PreDestroy;

@Service
public class MqttPublisherService {

    private static final String BROKER_URL = "tcp://localhost:1883"; // EMQX 服务器地址
    private static final String CLIENT_ID = "MqttPublisher";
    private static final String TOPIC = "devicetopic"; // 消息主题

    private final MqttClient mqttClient;

    @Autowired
    public MqttPublisherService(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
//        init();
    }

//    private void init() {
//        try {
//            MqttConnectOptions options = new MqttConnectOptions();
//            options.setCleanSession(true);
//            mqttClient.connect(options);
//            System.out.println("MQTT 发布客户端连接成功！");
//        } catch (MqttException e) {
//            e.printStackTrace();
//        }
//    }

    public void publishMessage(String message) {
        try {
            MqttMessage mqttMessage = new MqttMessage(message.getBytes());
            mqttMessage.setQos(1); // 设置 QoS
            mqttClient.publish(TOPIC, mqttMessage);
            System.out.println("消息已发布: " + message);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void cleanup() {
        try {
            mqttClient.disconnect();
            System.out.println("MQTT 发布客户端已断开连接.");
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}